//
//  HICTabBar.swift
//  vibo
//
//  Created by jht-seven on 16/6/25.
//  Copyright © 2016年 jht-seven. All rights reserved.
//

import UIKit
// 声明协议
protocol HICTabBarDelegate: NSObjectProtocol{
    // 声明协议方法
    func composeButtonClick()
}

class HICTabBar: UITabBar {
    
    // 声明代理
    // 使用weak 修饰代理需要继承NSObjectProtocol 基协议
    weak var hicDelegate:HICTabBarDelegate?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //UITabBarButton 的 宽度
        let width = SCREENW / 5
        // 纪录标识
        var index: CGFloat = 0
        //UITabBarButton
        
        // 通过遍历得到其类身上的子控件
        for value in self.subviews {
            // 判断其是UITabBarButton
            // 因为UITabBarButton 是真实存在的 不会为nil
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                // 设置宽度
                value.frame.size.width = width
                // 设置x轴
                value.frame.origin.x = index * width
                
                index++
                // 为了给我们撰写按钮留下位置
                if index == 2{
                    index++
                }
            }
        }
        
        //设置撰写按钮的frame
        composeButton.center.x = self.frame.width * 0.5
        composeButton.center.y = self.frame.height * 0.5
    }
    
    //设置视图
    func setupUI(){
        addSubview(composeButton)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 监听方法 (如果私有后 需要添加@objc 防止程序找不到该方法)
    @objc private func buttonClick(){
        hicDelegate?.composeButtonClick()
    }
    
    private lazy var composeButton : UIButton = {
        let button = UIButton()
        
        // 添加事件
        button.addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        //background image
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        
        //image
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        
        button.sizeToFit()
        
        return button
    }()
}
